package bzapps.weynak;

import java.io.IOException;

import org.json.JSONObject;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;
import bzapps.weynak.fb.SessionStore;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.Facebook;
 
public class UpdateLocationService extends Service implements LocationListener {

    private LocationManager locationManager;

    private final static long MIN_TIME = 0;

    private final static float MIN_DIST = 0;

    private SharedPreferences pref;
	
    private final static String LAST_LATITUDE = "LAST_LATITUDE";

    private final static String LAST_LONGITUDE = "LAST_LONGITUDE";

    static final String APP_ID = "119791898115838";
	private Facebook mFacebook;
    private AsyncFacebookRunner mAsyncFacebookRunner;
    
    public static final Criteria getCriteria()
    {
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_COARSE);
        criteria.setAltitudeRequired(true);
        criteria.setBearingRequired(false);
        criteria.setCostAllowed(false);
        criteria.setPowerRequirement(Criteria.POWER_LOW);
        criteria.setSpeedRequired(false);

        return criteria;
    }

    @Override
    public IBinder onBind(Intent arg0)
    {
        throw new UnsupportedOperationException();
    }

    @Override
    public void onCreate()
    {
        super.onCreate();
        	
        pref = PreferenceManager.getDefaultSharedPreferences(this);
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    }

    
    @Override
    public void onStart(Intent intent, int startId)
    {       
        super.onStart(intent, startId);

        String provider = locationManager.getBestProvider(getCriteria(), true);
        if (provider != null) {
            locationManager.requestLocationUpdates(provider, MIN_TIME, MIN_DIST, this);
        } else {
            stopSelf();
        }
    }

    @Override
    public void onLocationChanged(final Location location)
    {
        	String lastLatitude = pref.getString(LAST_LATITUDE, "0");
        	String lastLongitude = pref.getString(LAST_LONGITUDE, "0");
        	String user_name = pref.getString("FirstName", "Unkown")+ " " + pref.getString("LastName", "Unkown");
        	String uid = pref.getString("uid", "0");
        	Boolean permissionCheck = pref.getBoolean("weynak.auto_publish", false);
        	String distance = pref.getString("weynak.distance.interval", "5"); // 5km by default
        	boolean needUpdate = WeynakUtils.distanceKm(Double.parseDouble(lastLatitude), Double.parseDouble(lastLongitude),
                location.getLatitude(), location.getLongitude()) >= Double.parseDouble(distance);

        if (needUpdate) {
                try {
					boolean success = ClientOperations.update(user_name, uid, location.getLatitude(),location.getLongitude(), "1");
			
                if (success) {
            		WeynakUtils.sentNotification(getApplicationContext(), "Location updated");
                    pref.edit().putString(LAST_LATITUDE, Double.toString(location.getLatitude())).putString(LAST_LONGITUDE,
                            Double.toString(location.getLongitude())).commit();
                    Log.v("WEYNAK.update.location", "Operation successful");
                	}
                } catch (Exception e) {
					Log.e("WEYNAK.update.location", e.getMessage());
				}

                    if (permissionCheck) {
                    	try {
                    		mFacebook = new Facebook(APP_ID);
                    	   	mAsyncFacebookRunner = new AsyncFacebookRunner(mFacebook);
                    	    SessionStore.restore(mFacebook, this);
                    		if (mFacebook.isSessionValid()) {
                    		    Bundle parameters = new Bundle();
                    		    String address = WeynakUtils.getAddress(UpdateLocationService.this, location);
                    		    parameters.putString("message", "Hey I'm at " + address);
                    		    try {
                    				String response = mFacebook.request("me/feed", parameters,"POST");
                    			} catch (IOException e) {
                    			}
                    		}
                    	} catch(Exception e){
							Log.e("WEYNAK.publish.location", e.getMessage());
						}
                    }
        		}
        // fetch 
        
        else {
            Log.d("WEYNAK.update.location", "not necessary");
        }

        locationManager.removeUpdates(this);
        stopSelf();
    }
    
    @Override
    public void onProviderDisabled(String provider)
    {
    }

    @Override
    public void onProviderEnabled(String provider)
    {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras)
    {
    }
}
